//
//  YMSPictureView.swift
//  YMSWeibo
//
//  Created by 杨茂盛 on 2016/11/16.
//  Copyright © 2016年 杨茂盛. All rights reserved.
//

import UIKit
private let cellId = "YMSPictureCell"
class YMSPictureView: UICollectionView {

    var pictureInfos:[YMSPicture]?{
        didSet{
        //外界给配图视图设置数据的时候就会执行
            self.reloadData()
        }
    }
    
    override func awakeFromNib() {
        //注册cell
        let pictureCellNib = UINib(nibName: "YMSPictureCell", bundle: nil)
        self.register(pictureCellNib, forCellWithReuseIdentifier: cellId)
        self.dataSource = self
        
        //设置代理
        self.delegate = self
    }
}
extension YMSPictureView:UICollectionViewDataSource,UICollectionViewDelegate{
    //实现数据源方法
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pictureInfos?.count ?? 0
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! YMSPictureCell
        let pictureInfo = self.pictureInfos![indexPath.row]
        cell.pictureInfo = pictureInfo
        return cell
    }
    
    //实现代理方法
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        //显示图片浏览器
        
        //1. 实例化图片浏览器对象
        let borwser = SDPhotoBrowser()
        //设置容器视图 父视图
        borwser.sourceImagesContainerView = self
        borwser.currentImageIndex = indexPath.item
        borwser.imageCount = pictureInfos?.count ?? 0
        //设置代理
        borwser.delegate = self
        //显示图片浏览器
        borwser.show()

    }
    
}

extension YMSPictureView: SDPhotoBrowserDelegate {
    
    //返回高质量图片的url对象
    func photoBrowser(_ browser: SDPhotoBrowser!, highQualityImageURLFor index: Int) -> URL! {
        let picinfo = self.pictureInfos![index]
        let url = URL(string:picinfo.bimiddleImage ?? "")
        return url
    }
    
    //返回一个占位的图片
    func photoBrowser(_ browser: SDPhotoBrowser!, placeholderImageFor index: Int) -> UIImage! {
        //获取cell
        let indexPath = IndexPath(item: index, section: 0)
        let cell = self.cellForItem(at: indexPath) as? YMSPictureCell
        return cell?.imageView.image
        
    }
}
